//
//  MyInfoController.m
//  collection
//
//  Created by 靖 张 on 11/26/11.
//  Copyright (c) 2011 Tsinghua University. All rights reserved.
//

#import "MyInfoController.h"
#import "AppDelegate.h"
#import "CollectionDataManager.h"
#import <QuartzCore/QuartzCore.h>

@interface MyInfoController()

@property (nonatomic, strong)   IBOutlet    UIImageView*    avatarView;
@property (nonatomic, strong)   IBOutlet    UILabel*        birthdayLabel;
@property (retain, nonatomic) IBOutlet UITextField *        nicknameLabel;
@property (retain, nonatomic) IBOutlet UITextView *signatureText;
@property (nonatomic, assign)   UIActionSheet*  actionSheet;
@property (nonatomic, retain)   UIToolbar*  actionBar;

- (IBAction)onClickBackBarItem:(id)sender;
- (IBAction)onClickFinishModify:(id)sender;
- (void)loadPersonalInfo;
- (void)onClickAvatar:(id)sender;
- (void)onClickBirthdayLabel:(id)sender;
- (void)onCloseDatePicker:(id)sender;
- (void)onDatePickerValueChanged:(id)sender;
- (void)onTapThisView:(id)sender;
- (void)onCloseInputView:(id)sender;

@end

@implementation MyInfoController

@synthesize avatarView = _avatarView;
@synthesize birthdayLabel = _birthdayLabel;
@synthesize nicknameLabel = _nicknameLabel;
@synthesize signatureText = _signatureText;
@synthesize actionSheet = _actionSheet;
@synthesize actionBar = _actionBar;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UIImageView* imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"top_info_on"]];
        self.navigationItem.titleView = imgView;
        [imgView release];
    }
    return self;
}

- (void)dealloc {
    
    self.avatarView = nil;
    self.birthdayLabel = nil;
    self.actionSheet = nil;
    self.actionBar = nil;
    [_nicknameLabel release];
    [_signatureText release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)loadView {

    [super loadView];
    
    // Background
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"all_bg"]];
    
    UITapGestureRecognizer* imageTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickAvatar:)];
    [self.avatarView addGestureRecognizer:imageTapGestureRecognizer];
    [imageTapGestureRecognizer release];
    
    // Input access view
    UIToolbar* toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    toolBar.barStyle = UIBarStyleBlackTranslucent;
    [toolBar sizeToFit];
    
    NSMutableArray* barButtons = [[NSMutableArray alloc] init];
    UIBarButtonItem* flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    [barButtons addObject:flexSpace];
    [flexSpace release];
    
    UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(onCloseInputView:)];
    [barButtons addObject:doneButton];
    [doneButton release];
    
    [toolBar setItems:barButtons animated:YES];
    [barButtons release];
    
    self.actionBar = toolBar;
    [toolBar release];
/*    
    UIDatePicker* datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 40, 0, 0)];
    datePicker.datePickerMode = UIDatePickerModeDate;
    [datePicker addTarget:self action:@selector(onDatePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
*/    
    self.birthdayLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer* labelTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickBirthdayLabel:)];
    [self.birthdayLabel addGestureRecognizer:labelTapRecognizer];
    [labelTapRecognizer release];
    
    self.avatarView.layer.masksToBounds = YES;
    self.avatarView.layer.cornerRadius = 5;
    
    self.signatureText.inputAccessoryView = self.actionBar;
/*
    UITapGestureRecognizer* viewTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapThisView:)];
    [self.view addGestureRecognizer:viewTapRecognizer];
    [viewTapRecognizer release];
*/
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self loadPersonalInfo];
}

- (void)viewDidUnload
{
    [self setNicknameLabel:nil];
    [self setSignatureText:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.avatarView = nil;
    self.birthdayLabel = nil;
    self.actionSheet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Private methods

- (IBAction)onClickBackBarItem:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)onClickFinishModify:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)loadPersonalInfo {
    
    CollectionDataManager* dataManager = [CollectionDataManager sharedInstance];
    UserInfo* user = dataManager.currentLoginUser;
    self.avatarView.image = user.avatar;
    self.nicknameLabel.text = user.nickname;
    self.birthdayLabel.text = @"2011-11-06";
    self.signatureText.text = user.signature;
}

- (void)onClickAvatar:(id)sender {

    if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [appDelegate.rootNavigationController presentModalViewController:imagePickerController animated:YES];
        [imagePickerController release];
        return;
    }
    
    UIActionSheet* imageActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"相册选择", nil];
    imageActionSheet.tag = 1;
    [imageActionSheet showInView:self.view];
    self.actionSheet = imageActionSheet;
    [imageActionSheet release];
}

- (void)onClickBirthdayLabel:(id)sender {
    
    // Toolbar
    UIToolbar* datePickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    datePickerToolbar.barStyle = UIBarStyleBlackTranslucent;
    [datePickerToolbar sizeToFit];
    datePickerToolbar.tag = 1;
    
    NSMutableArray* barButtons = [[NSMutableArray alloc] init];
    UIBarButtonItem* flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    [barButtons addObject:flexSpace];
    [flexSpace release];
    
    UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(onCloseDatePicker:)];
    [barButtons addObject:doneButton];
    [doneButton release];
    
    [datePickerToolbar setItems:barButtons animated:YES];
    [barButtons release];
    
    // Date picker
    UIDatePicker* datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, datePickerToolbar.frame.size.height, 0, 0)];
    datePicker.datePickerMode = UIDatePickerModeDate;
    [datePicker addTarget:self action:@selector(onDatePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
    datePicker.tag = 2;
    
    // Action sheet
    UIActionSheet* birthdayActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
    birthdayActionSheet.tag = 2;
    [birthdayActionSheet addSubview:datePickerToolbar];
    [birthdayActionSheet addSubview:datePicker];
    [datePickerToolbar release];
    [datePicker release];
    
    [birthdayActionSheet showInView:self.view];
    self.actionSheet = birthdayActionSheet;
    [birthdayActionSheet setBounds:CGRectMake(0, 0, 320, 464)];
    [birthdayActionSheet release];
}

- (void)onCloseDatePicker:(id)sender {
    
    if (self.actionSheet == nil) {
        return;
    }
    
    UIView* view = [[self.actionSheet subviews] objectAtIndex:1];
    if (![view isMemberOfClass:[UIDatePicker class]]) {
        return;
    }
    
    UIDatePicker* datePicker = (UIDatePicker*)view;
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    self.birthdayLabel.text = [formatter stringFromDate:datePicker.date];    
    [formatter release];
    
    [self.actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)onCloseInputView:(id)sender {
    
    [self.signatureText resignFirstResponder];
    
    CGRect frame = self.view.frame;
    [self animateView:frame.origin.y];
}

- (void)onDatePickerValueChanged:(id)sender {
   
    UIDatePicker* datePicker = (UIDatePicker*)sender;
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    NSLog(@"Date : %@", [dateFormatter stringFromDate:datePicker.date]);
    
    [dateFormatter release];
}

- (void)onTapThisView:(id)sender {
/*
    for (UIView* view in [self.view subviews]) {
        [view resignFirstResponder];
    }
*/
}

#pragma mark - Implementation of UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    textField.textColor = [UIColor colorWithRed:51.0 / 255.0 green:51.0 / 255.0 blue:51.0 / 255.0 alpha:1];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    textField.textColor = [UIColor colorWithRed:187.0 / 255.0 green:187.0 / 255.0 blue:187.0 / 255.0 alpha:1];
    [textField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    
    return YES;
}

#pragma mark - [UITextViewDelegate]

- (void)textViewDidBeginEditing:(UITextView *)textView {
    
    textView.textColor = [UIColor colorWithRed:51.0 / 255.0 green:51.0 / 255.0 blue:51.0 / 255.0 alpha:1];
    
    CGFloat aim = 460 - self.signatureText.inputAccessoryView.superview.frame.size.height;
    CGFloat height = self.signatureText.frame.origin.y + self.signatureText.frame.size.height;
    if (height > aim) {
        [self animateView:(height - aim)];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    
    textView.textColor = [UIColor colorWithRed:187.0 / 255.0 green:187.0 / 255.0 blue:187.0 / 255.0 alpha:1];
}

#pragma mark - Implementation of UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    self.actionSheet = nil;
    
    if (actionSheet.tag != 1) {
        return;
    }
    
    UIImagePickerControllerSourceType sourceType;
    if (buttonIndex == 0) {
        sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    else if (buttonIndex == 1) {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    else {
        [self dismissModalViewControllerAnimated:YES];
        return;
    }
    
    UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.rootNavigationController presentModalViewController:imagePickerController animated:YES];
    [imagePickerController release];
}

#pragma mark - Implementation of UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    UIImage* editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
    if (editedImage != nil) {
        self.avatarView.image = editedImage;
    }
    
    //   [self dismissModalViewControllerAnimated:YES];
    [picker dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [picker dismissModalViewControllerAnimated:YES];
}

#pragma mark - [Private methods]

- (void)animateView:(NSInteger)moveUpHeight {
    
    CGRect rect = self.view.frame;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    
    //    if (moveUpHeight > 0) 
    {
        rect.origin.y -= moveUpHeight;
    }
    
    self.view.frame = rect;
    [UIView commitAnimations];
}

@end
